import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'
import { C } from '@angular/core/src/render3'

declare var $: any
declare var echarts: any
declare var Viewer: any
@Component({
  selector: 'sa-incoming-inspect-report',
  templateUrl: './incoming-inspect-report.component.html',
  styleUrls: ['./incoming-inspect-report.component.css']
})
export class IncomingInspectReportComponent implements OnInit {
  validatorOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      checkDate: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择检验日期'
          }
        }
      },
      materialCode: {
        validators: {
          notEmpty: {
            message: '请输入物料编码'
          }
        }
      },
      materialName: {
        validators: {
          notEmpty: {
            message: '请输入物料名称'
          }
        }
      },
      materialDesc: {
        validators: {
          notEmpty: {
            message: '请输入物料规格描述'
          }
        }
      },
      supplier: {
        validators: {
          notEmpty: {
            message: '请输入供应商'
          }
        }
      },
      materialType: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择物料类别'
          }
        }
      },
      comMaterialNum: {
        validators: {
          notEmpty: {
            message: '请输入来料数量'
          }
        }
      },
      spotCheckNum: {
        validators: {
          notEmpty: {
            message: '请输入抽检数量'
          }
        }
      },
      badNumber: {
        validators: {
          notEmpty: {
            message: '请输入不良数量'
          }
        }
      },
      checkResult: {
        trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择检验结果'
          }
        }
      },
      examiner: {
        validators: {
          notEmpty: {
            message: '请输入检验员'
          }
        }
      }
    }
  }
  fromType: any = ''
  tableData = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  searchKey: string = '' //搜索keyword
  startTime: string = ''
  endTime: string = ''
  faultPhenomenon: string = ''
  formType: string = 'new'

  isShowAdd: boolean = false
  isShowDel: boolean = false
  isShowEdit: boolean = false

  tableSearch: any = {
    checkDate: '', //检验日期
    materialCode: '', //物料编码
    materialName: '', //物料名称
    supplier: '', //供应商
    materialType: '', //物料类别
    checkResult: '' //检验结果
  }

  IncomingInspectReportForm: any = {
    id: '',
    checkDate: '', //检验日期
    materialCode: '', //物料编码
    materialName: '', //物料名称
    materialDesc: '', //物料规格描述
    supplier: '', //供应商
    materialType: '', //物料类别
    comMaterialNum: '', //来料数量
    spotCheckNum: '', //抽检数量
    badNumber: '', //不良数量
    checkResult: '', //检验结果
    descOfBad: '', //不良现象描述
    descOfHandle: '', //处理对策
    examiner: '', //检验员
    imageOfBad: '', //不良现象图片
    imageOfHandle: '', //处理对策图片
    createTime: '', //创建时间
    createName: '' //创建人
  }

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }

  ngOnInit() {
    this.initBtn()
    System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
      System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
        this.initDate()
        $('#datetimepicker1')
          .datetimepicker({
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeDay(date)
            this.startTime = time
            $('#datetimepicker2').datetimepicker('setStartDate', time)
          })
        $('#datetimepicker2')
          .datetimepicker({
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeDay(date)
            this.endTime = time
            $('#datetimepicker1').datetimepicker('setEndDate', time)
          })
        let that = this
        $('#inspectDateAdd')
          .datetimepicker({
            format: 'yyyy-mm-dd',
            language: 'zh-CN',
            autoclose: true,
            minView: 2
          })
          .on('changeDate', function (e) {
            var date = e.date
            var time = common.getTimeDay(date)
            that.IncomingInspectReportForm.checkDate = time
          })
      })
    })
    this.load()
  }

  initDate() {
    // common.initDatePicker('#checkDate', 1)
    // common.initDatePicker('#inspectDateAdd', 1)
    // let nowTime = new Date().toLocaleDateString().replace(/\//g,'-');
    // $('#inspectDateAdd').val(nowTime) //当前时间
  }

  //初始化权限按钮
  initBtn() {
    var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_supplyChain:incomingInspectReport')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'incomingInspectReport:addBtn' && item.parentId) {
        this.isShowAdd = true
      }
      if (item.sourceKey === 'incomingInspectReport:delBtn' && item.parentId) {
        this.isShowDel = true
      }
      if (item.sourceKey === 'incomingInspectReport:editBtn' && item.parentId) {
        this.isShowEdit = true
      }
    }
  }

  /*
   * 新增
   */
  table_add(modal) {
    modal.show()
    this.resetForm()
    this.formType = 'new'
  }

  // 编辑项目事件
  editRow(row, modal) {
    this.formType = 'updata'
    this.resetForm()
    for (let key in this.IncomingInspectReportForm) {
      this.IncomingInspectReportForm[key] = row[key]
    }
    this.IncomingInspectReportForm.checkDate = row.checkDate.substring(0, 10)

    this.IncomingInspectReportForm.imageOfBad = row.imageOfBad ? row.imageOfBad.split(',') : []
    this.IncomingInspectReportForm.imageOfHandle = row.imageOfHandle ? row.imageOfHandle.split(',') : []

    modal.show()
  }

  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
  }

  resetForm() {
    $('#IncomingInspectReportForm').data('bootstrapValidator').resetForm()
    let nowTime = new Date().toLocaleDateString().replace(/\//g, '-')
    this.IncomingInspectReportForm = {
      id: '',
      checkDate: '', //检验日期
      materialCode: '', //物料编码
      materialName: '', //物料名称
      materialDesc: '', //物料规格描述
      supplier: '', //供应商
      materialType: '', //物料类别
      comMaterialNum: '', //来料数量
      spotCheckNum: '', //抽检数量
      badNumber: '', //不良数量
      checkResult: '', //检验结果
      descOfBad: '', //不良现象描述
      descOfHandle: '', //处理对策
      examiner: '', //检验员
      imageOfBad: [], //不良现象图片
      imageOfHandle: [], //处理对策图片
      createTime: '', //创建时间
      createName: '' //创建人
    }
  }

  /**
   * 图片的方法
   */
  isViewer: boolean = false //默认隐藏

  //显示图片组件
  viewer: any = ''
  fileList: File = null

  bigImgClick() {
    // modal.show();
    if (this.isViewer && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showImg()
          })
        })
      })
    } else {
      this.showImg()
    }
  }

  showImg() {
    var imgList = $('.imgFileList')[0]
    this.viewer = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer = true
  }

  //上传多张
  multifileChange(files: FileList, str: string) {
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
    let multfileList = files
    var reqdata = new FormData()
    let describe = ''
    if (str === 'imageOfBad') {
      describe = '不良现象图片'
    } else {
      describe = '处理对策图片'
    }
    reqdata.append('describe', describe)
    reqdata.append('businessType', '3')
    reqdata.append('type', '2') //type 1获取相对路径  2获取绝对路径
    for (var i = 0; i < multfileList.length; i++) {
      this.fileList = multfileList[i]
      const isJPG =
        this.fileList.type === 'image/jpeg' || this.fileList.type === 'image/jpg' || this.fileList.type === 'image/png'
      if (!isJPG) {
        this.jsonApiService.message('上传图片只能是 png, jpg, jpeg 格式!')
        return
      }
      reqdata.append('files', multfileList[i])
    }
    this.jsonApiService.form_http('fileUpload/upload.html', reqdata).subscribe(data => {
      if (data.success) {
        for (var i = 0; i < data.data.length; i++) {
          this.IncomingInspectReportForm[str].push(data.data[i])
        }
      }
    })
    for (let k = 0; k < $('.up').length; k++) {
      $('.up')[k].value = null
    }
  }

  //删除图片
  deleteImg(index, i, str) {
    if (index == 1) {
      this.IncomingInspectReportForm[str].splice(i, 1)
    }
    if (this.isViewer && $('.viewer-container').length > 0) {
      this.viewer.destroy()
    }
  }

  /*
   * form提交
   */
  apiControlSubmit(modal) {
    $('#IncomingInspectReportForm').bootstrapValidator('validate') //开启验证
    let isValid = $('#IncomingInspectReportForm').data('bootstrapValidator').isValid() //验证是否通过
    if (isValid) {
      const formData = JSON.parse(JSON.stringify(this.IncomingInspectReportForm))
      formData.imageOfBad = this.IncomingInspectReportForm.imageOfBad.join(',')
      formData.imageOfHandle = this.IncomingInspectReportForm.imageOfHandle.join(',')
      formData.checkDate = formData.checkDate + ' 00:00:00'

      this.jsonApiService.http_obj('matterCheck/editMatterCheck.html', formData).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
          this.modalClose(modal)
        }
      })
    }
  }

  //删除所选时间
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.searchKey = common.stringTrim(this.searchKey)
    this.load()
  }
  //初始化加载list数据
  load() {
    this.startTime = $('#datetimepicker1').val()
    this.endTime = $('#datetimepicker2').val()
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: {
        startTime: this.startTime ? this.startTime + ' 00:00:00' : '',
        endTime: this.endTime ? this.endTime + ' 00:00:00' : '',
        ...this.tableSearch
      }
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('matterCheck/matterCheckPageList.html', reqdata).subscribe(result => {
      this.tableData = result.data.exhibitDatas || []
      this.totalCount = result.data.recordCount
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  // 导出
  dataExceport() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      isExport: 1,
      parameters: {
        startTime: this.startTime ? this.startTime + ' 00:00:00' : '',
        endTime: this.endTime ? this.endTime + ' 00:00:00' : '',
        ...this.tableSearch
      }
    }

    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'matterCheck/matterCheckPageList.html')
  }
  deleteRow(row) {
    this.jsonApiService.confirm_message('删除该条来料检验报表，确认要删除?').then(() => {
      let reqdata = 'id=' + row.id
      this.jsonApiService.http('matterCheck/deleteMatterCheck.html', reqdata).subscribe(data => {
        this.jsonApiService.message(data.message)
        if (data.success) {
          this.load()
        }
      })
    })
  }

  /**
   * 图片的方法
   */
  imgList: any = []
  imgLocalList: any = []
  isViewer1: boolean = false //默认隐藏
  //显示图片组件
  viewer1: any = ''

  // 点击Table中的查看图片
  showImg1(imagePath, modal) {
    this.imgList = []
    this.imgLocalList = []
    this.imgList = imagePath.split(',')
    let localImg
    for (var i = 0; i < this.imgList.length; i++) {
      localImg = this.imgList[i]
      this.imgLocalList.push(localImg)
    }
    modal.show()
    if (this.isViewer1 && $('.viewer-container').length > 0) {
      this.viewer1.destroy()
    }
  }

  bigimg() {
    if (this.isViewer1 && $('.viewer-container').length > 0) {
      System.import('assets/js/viewer/viewer.js').then(() => {
        System.import('assets/js/viewer/bootstrap.bundle.min.js').then(() => {
          System.import('assets/js/viewer/viewer.css').then(() => {
            this.showBigImg()
          })
        })
      })
    } else {
      this.showBigImg()
    }
  }

  showBigImg() {
    var imgList = $('.imagesInfo1')[0]
    this.viewer1 = new Viewer(imgList, {
      url: 'src',
      title: function (image) {
        return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')'
      }
    })
    this.isViewer1 = true
  }

  // 关闭图片查看
  closeImgModal1(modal) {
    modal.hide()
    this.imgList = []
    this.imgLocalList = []
  }

  validateChange(str) {
    this.IncomingInspectReportForm[str] = this.IncomingInspectReportForm[str].replace(/[^\d]/g, '')
  }
}
